package universe;

import gui.UniverseFrame;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import universe.forces.Force;
import universe.forces.GravityForce;
import universe.utils.Vector3D;

public class Universe {

	private List<CelestialBody> bodiesInUniverse;
	private Force gravityForce;
	private double age;

	public Universe() {
		bodiesInUniverse = new ArrayList<CelestialBody>();
		gravityForce = new GravityForce();
		age = 0;
	}

	public void update(double interval) {
		for (CelestialBody cb : bodiesInUniverse) {
			Vector3D f = resultantForce(cb);
			cb.update(f, UniverseFrame.timeInterval);
		}
		// Check for collisions
		age += interval;
	}

	public void add(CelestialBody cb) {
		bodiesInUniverse.add(cb);
	}

	private Vector3D resultantForce(CelestialBody cb) {
		Vector3D fRes = new Vector3D();
		for (CelestialBody other : bodiesInUniverse) {
			if (other != cb) {
				Vector3D f = gravityForce.getInteractionForceBetween(cb, other);
				fRes.add(f);
			}
		}
		return fRes;
	}

	private Collection<CelestialBody> bodiesInCollisionWith(CelestialBody target) {
		List<CelestialBody> bodiesInCollision = new ArrayList<CelestialBody>();

		for (CelestialBody cb : bodiesInUniverse) {
			if (bodiesAreInCollision(target, cb)) {
				bodiesInCollision.add(cb);
			}
		}

		return bodiesInCollision;
	}

	private boolean bodiesAreInCollision(CelestialBody c1, CelestialBody c2) {
		if (c1 == c2) {
			return false;
		}
		// double minDistance = c1.getRadius() + c2.getRadius();
		// return c1.getPosition().distanceTo(c2.getPosition()) < minDistance;
		return true;
	}

	public Collection<CelestialBody> bodiesInUniverse() {
		return new ArrayList<CelestialBody>(bodiesInUniverse);
	}

	public double age() {
		return age;
	}
}
//
//
//
//
//
